use mysql::{Opts, OptsBuilder, Pool};
use serde::Deserialize;
//use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read};
use toml;

const GLOB_CONFIG: &str = "config.fb";
static mut MYSQL_DATA_SOURCE: MysqlDataSource = MysqlDataSource { pool: None };

#[derive(Deserialize)]
struct MysqlConfig {
    user: String,
    host: String,
    password: String,
    port: u16,
}
#[derive(Deserialize)]
struct GlobConfig {
    mysql: MysqlConfig,
}

pub struct MysqlDataSource {
    pool: Option<Pool>,
}

///
pub fn init_mysql_ds() {
    let file = File::open(GLOB_CONFIG).unwrap();
    let mut buf_reader = BufReader::new(file);
    let mut config_string = String::new();
    buf_reader.read_to_string(&mut config_string).unwrap();
    let glob_config: GlobConfig = toml::from_str(&config_string).unwrap();
    unsafe {
        let mut builder = OptsBuilder::default();
        builder
            .user(Some(glob_config.mysql.user))
            .pass(Some(glob_config.mysql.password))
            .ip_or_hostname(Some(glob_config.mysql.host))
            .tcp_port(glob_config.mysql.port);
        //            .db_name(Some("dev_order"));
        let opts: Opts = builder.into();
        let pool = Pool::new(opts).unwrap();
        MYSQL_DATA_SOURCE.pool = Some(pool);
    }
}

pub fn get_mysql_conn_pool() -> Option<&'static Pool> {
    unsafe { MYSQL_DATA_SOURCE.pool.as_ref() }
}
